<template>
  <el-drawer :model-value="isShowLimit" size="30%" @close="closeAll">
    <template #header="{}">
      <div class="flex items-center justify-start">
        <div class="flex items-center justify-start flex-1">
          <el-icon @click="returnBack"><ArrowLeftBold /></el-icon>
          <p class="flex-1">{{ $t("设置限额") }}</p>
        </div>
      </div>
    </template>
    <el-card v-loading="loading">
      <h4 class="text-large">{{ $t("卡片总金额") }}</h4>
      <p class="mt-2 mb-3">
        {{ numberToCurrencyNo(totalAmount) }}
        {{ detailInfo.currency }}
      </p>
      <el-row
        :gutter="20"
        class="mb-2"
        v-for="(condition, index) in state.searchConditions"
        :key="index"
      >
        <el-col :span="10">
          <el-input
            ref="inputRef"
            :placeholder="$t('请设置限额')"
            v-model="condition.amount"
            type="number"
            @change="(val) => onChange(val, condition)"
          ></el-input>
          <span class="text-[#e54c5f] text-xs">{{ condition.tips }}</span>
        </el-col>
        <el-col :span="10">
          <el-select
            :placeholder="$t('请选择')"
            v-model="condition.interval"
            @change="(val) => onChange(val, condition)"
          >
            <el-option
              v-for="item in cardLimits"
              :key="item.value"
              :label="item.name"
              :value="item.value"
              :disabled="selectItems.includes(item.value)"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-icon @click="removeLimit(index)"><Delete /></el-icon>
        </el-col>
      </el-row>
      <!-- 条件只能四条 -->
      <el-button
        link
        type="danger"
        @click="addLimit"
        v-if="state.searchConditions.length < 4"
        >{{ $t("增加一个限额") }}</el-button
      >
    </el-card>
    <div class="flex justify-center mt-6 align-center">
      <el-button type="danger" size="large" class="w-20" @click="saveLimit">{{
        $t("保存")
      }}</el-button>
    </div>
  </el-drawer>
</template>
<script setup>
import { ref, watch, reactive, computed } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { numberToCurrencyNo } from "@/utils/utils";
import Record from "./record.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { GetCardsLimits, setCardLimits } from "@/api/card";

const props = defineProps({
  isShowLimit: {
    type: Boolean,
    default: false,
  },
  cardId: {
    type: String,
    default: "",
  },
  totalAmount: {
    type: String,
    default: "",
  },
  detailInfo: {
    type: Object,
    default: () => {},
  },
  cardLimits: {
    type: Array,
    default: () => [],
  },
});

const state = reactive({
  limits: [],
  searchConditions: [],
});

const emits = defineEmits(["close", "refreshList", "closeAll"]);
const returnBack = () => {
  emits("close");
};

const closeAll = () => {
  emits("closeAll");
};

watch(
  () => props.isShowLimit,
  async (val) => {
    if (val) {
      await getCardsLimits();
      if (
        state.limits.length === 1 &&
        state.limits[0].amount === 10000 &&
        state.limits[0].interval === "PER_TRANSACTION"
      ) {
        state.searchConditions = state.searchConditions;
      } else {
        if (state.limits.length > 0) {
          state.searchConditions = state.limits.map((item) => {
            return {
              amount: item.amount,
              interval: item.interval,
            };
          });
        }
      }
    }
  }
);

// 获取卡片限额
const getCardsLimits = async () => {
  try {
    loading.value = true;
    const { limits } = await GetCardsLimits({ card_id: props.cardId });
    state.limits = limits || [];
    loading.value = false;
  } catch (e) {
    loading.value = false;
    console.log(e);
  }
};

const selectItems = computed(() => {
  return state.searchConditions.map((item) => {
    return item.interval;
  });
});
// 设置限额金额改变事件
const onChange = (val, condition) => {
  const intervalList = state.searchConditions.map((item) => {
    return item.interval;
  });
  state.searchConditions.forEach((item) => {
    if (item.interval === "DAILY") {
      state.dayLy_amount = Number(item.amount);
    } else if (item.interval === "WEEKLY") {
      state.week_amount = Number(item.amount);
    } else if (item.interval === "MONTHLY") {
      state.month_amount = Number(item.amount);
    }
    //判断大于总金额
    if (item.amount > Number(state.totalAmount)) {
      item.tips = t(`金额需要小于等于${state.totalAmount}`);
    } else {
      item.tips = "";
    }
    // 周必须大于等于日，月大于等于周
    if (
      item.interval === "WEEKLY" &&
      intervalList.includes("DAILY") &&
      item.amount < Number(state.totalAmount)
    ) {
      if (Number(item.amount) < state.dayLy_amount) {
        item.tips = t("需要大于等于每日限额");
      } else {
        item.tips = "";
      }
    } else if (
      item.interval === "MONTHLY" &&
      item.amount < Number(state.totalAmount)
    ) {
      if (
        intervalList.includes("DAILY") &&
        Number(item.amount) < state.dayLy_amount
      ) {
        item.tips = t("需要大于等于每日限额");
      } else if (
        intervalList.includes("WEEKLY") &&
        item.amount < state.week_amount
      ) {
        item.tips = t("需要大于等于每周限额");
      } else {
        item.tips = "";
      }
    }
  });
};

// 添加限额
const addLimit = () => {
  state.searchConditions.push({ amount: "", interval: "" });
};

// 删除限额
const removeLimit = (index) => {
  state.searchConditions.splice(index, 1);
  onChange();
};

const loading = ref(false);

// 设置限额保存
const saveLimit = async () => {
  const searchConditions = state.searchConditions.map((item) => {
    if (Object.keys(item).includes("amount") && item.amount !== "") {
      return item;
    }
    return undefined;
  });
  const conditions = searchConditions.filter(Boolean); // 筛选出来不为空的
  if (conditions.length === 0) {
    ElMessage({
      type: "warning",
      message: "请添加限额",
    });
  } else {
    const tips = conditions.filter((item) => {
      if (item.tips && item.tips !== "") {
        return item;
      }
    });
    // 判断是否有限额错误
    if (tips.length < 1) {
      try {
        loading.value = true;
        const res = await setCardLimits({
          card_id: props.cardId,
          limits: conditions,
        });
        if (res) {
          ElMessage({
            type: "success",
            message: `${t("设置成功")}`,
          });
          loading.value = false;
          emits("closeAll");
        }
      } catch {}
    } else {
      nextTick(() => {
        conditions.forEach((item, index) => {
          if (item.tips !== "") {
            inputRef.value[index].focus();
          }
        });
      });
    }
  }
};
</script>
